/***
 * 并查集Version1
 */
public class UnionFind1 implements UF{
    private int[] id;

    public UnionFind1(int size){
        id = new int[size];
        for(int i=0;i<size;i++){
            id[i] = i;
        }
    }

    /***
     * 查询index号元素对应的集合值
     * @param index
     * @return
     */
    private int find(int index){
        if(index < 0 || index >= id.length)
            throw new IllegalArgumentException("index is out of bound");
        return id[index];
    }


    @Override
    public int getSize() {
        return id.length;
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElements(int p, int q) {
        int pId = find(p);
        int qId = find(q);
        if(pId == qId){
            //本来就在同一集合中
            return;
        }
        for(int i=0;i<id.length;i++){
            if(id[i] == pId){
                id[i] = qId;
            }
        }
    }
}
